package top.rainbowecho.notify.domain.model.email.decorator;

import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.util.StringUtils;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import top.rainbowecho.common.mq.mo.MailMeta;
import top.rainbowecho.common.util.ExceptionMessageContent;
import top.rainbowecho.notify.domain.model.email.EmailDecorator;
import top.rainbowecho.notify.domain.model.email.Mail;
import top.rainbowecho.notify.domain.model.email.db.entity.MailTemplate;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;

/**
 * 模板邮件发送装饰器为邮件发送设置模板内容
 *
 * @author rainbow
 * @since 2019/11/28 14:33
 */
public class TemplateMail extends EmailDecorator {
    public TemplateMail(Mail mail) {
        super(mail);
        this.setFrom(mail.getFrom());
        this.setSender(mail.getSender());
        this.setTemplateEngine(mail.getTemplateEngine());
        this.setTemplateMapper(mail.getTemplateMapper());
    }

    @Override
    public MimeMessage generateHtmlMail(MailMeta info) throws MessagingException, IOException {
        MimeMessage message = this.getMail().generateHtmlMail(info);

        if (!StringUtils.isEmpty(info.getTemplate())) {
            // 根据template进行查询
            String template = info.getTemplate();
            MailTemplate templateRecord = this.getTemplateMapper().findMailTemplateBySign(template);
            if (templateRecord == null) {
                throw new NullPointerException(ExceptionMessageContent.MAIL_TEMPLATE_NOT_EXIST);
            }

            String htmlContent = convert(this.getMail().getTemplateEngine(), info, templateRecord.getContext());
            // 根据传递的参数重新设置邮件内容
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setText(htmlContent, true);
            helper.setSubject(templateRecord.getSubject());
        }
        return message;
    }
    /**
     * 将模板文件内容转换成为文本
     *
     * @param templateEngine 模板引擎
     * @param info 元数据
     * @param html html文件内容
     * @return 生成的文本
     */
    static String convert(TemplateEngine templateEngine, MailMeta info, String html) {
        Context context = new Context();
        context.setVariables(info.getParams());
        return templateEngine.process(html, context);
    }
}
